package com.woniu.core.util;

import cn.hutool.json.JSONUtil;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;

import java.util.HashMap;
import java.util.Map;

public class ValidateUtil {
    /**
     * @description:返回参数错误信息
     * @author: yjx
     * @date: 2023/7/25 15:47
     * @param: [bindingResult]
     * @return: com.example.canteen.utils.Result
     **/
    public static Result<Map<String, Object>> getValidateError(BindingResult bindingResult) {

        if (!bindingResult.hasErrors()) {
            return null;
        }

        Map<String, String> fieldErrors = new HashMap<>();

        for (FieldError error : bindingResult.getFieldErrors()) {
            fieldErrors.put(error.getField(), error.getCode() + " | " + error.getDefaultMessage());
            System.out.println(error.getField()+"***"+error.getCode()+"***"+error.getDefaultMessage());
        }

        Map<String, Object> result = new HashMap<>();
        result.put("fieldErrors", fieldErrors);
//        System.out.println(result);
        return Result.getMapResult(String.class, Object.class).setMsg("参数错误").setCode(400).setData(result);
    }
}
